package com.pactera.utils;


import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;

public class Base64Utils {
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    public static final Charset GBK = Charset.forName("GBK");
    public static final String EMPTY_STRING = "";

    private Base64Utils() {
    }

    /**
     * 编码
     *
     * @param decode 明文
     * @return
     */
    public static String encode(String decode) {
        return encode(decode, UTF_8);
    }

    /**
     * 指定字符集-编码
     *
     * @param decode  明文
     * @param charset 字符集
     * @return
     */
    public static String encode(String decode, Charset charset) {
        if (StringUtils.isBlank(decode)) {
            return EMPTY_STRING;
        }
        byte[] bytes = Base64.encodeBase64(decode.getBytes(charset));
        return new String(bytes, charset);
    }

    /**
     * 解码
     *
     * @param encode 密文
     * @return
     */
    public static String decode(String encode) {
        byte[] bytes = Base64.decodeBase64(encode);
        return new String(bytes, UTF_8);
    }

    /**
     * 解码
     *
     * @param encode 密文
     * @return
     */
    public static String decode(String encode, Charset charset) {
        if (StringUtils.isBlank(encode)) {
            return EMPTY_STRING;
        }
        byte[] bytes = Base64.decodeBase64(encode);
        return new String(bytes, charset);
    }
}
